import { memo, useEffect, useMemo, useState, useRef } from 'react';
import { Input, Button, AutoComplete, Tag, message, Tooltip } from 'antd';
import type { AutoCompleteProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '@/components/icon';
const { TextArea } = Input;
import { useConfigActions, useInitializeData } from '@/store/configStore';
import { useNavigate } from 'react-router-dom';

import { CloseOutlined } from '@ant-design/icons';
import '../style/homepage.css';

import { useIsDeepMode, useChatActions, useIsOnlineMode } from '@/store/chatStore';
import { VariableItemType } from '@/types/app/type';

const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;
import LicenseModal from '@/pages/components/modal/LicenseConfirm';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { AppType, AppWorkbenchType } from '@/common/app/constants';
import orchestrationService from '@/api/services/orchestrationService';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { ChatBoxVariableInput } from '@/components/chat-box/VariableInputItem';
import { VariableInputEnum } from '@/types/workflow/constant';
import { fetchConfigStatus } from '@/utils/common';
import FunasrRecorder from '../../chat/components/FunasrRecorder';
import metahumanService from '@/api/services/metahumanService';
import { useMetahumanStore } from '@/store/metahumanStore';
import { useRequest } from 'ahooks';

// 定义引导问题类型
interface GuideQuestion {
  value: string;
}

interface Props {
  handleSend: (message: string) => void;
  handleInterrupt: () => void;
  changeInputType: () => void;
  isMessageSend: boolean;
  isHome: boolean;
  voice?: boolean;
  onChatStart?: (message: string) => void;
  onVoiceStop?: (message: string) => void;
  onInterrupt?: () => void;
  onSTT?: (message: number) => void;
  setHomepageChatStart?: (message: boolean) => void;
}

const MessageSendInput = ({
  handleSend,
  handleInterrupt,
  changeInputType,
  isMessageSend,
  isHome,
  voice,
  onChatStart,
  onInterrupt,
  onVoiceStop,
  onSTT,
  setHomepageChatStart,
}: Props) => {
  const {
    workflow,
    inputGuides,
    configurations,
    appDetail,
    setFusionAppId,
    fusionAppId,
    subAppDetail,
    setSubAppDetail,
    userSelectVariables,
    setVariables,
    variables: flowVariables,
  } = useOrchestrationStore();

  const {
    stop: storeStop,
    reset,
    setPermissionConfig, 
    setAppId,
    setIsPermissionConfigLoading, 
    setVirtualAvatarEnabled, 
    setVirtualAvatarId, 
    setVirtualSpeakerId, 
    setVirtualAvatarUrl, 
    setVirtualAvatarName, 
    setVirtualAvatarVoice 
  } = useMetahumanStore();

  const [isVoiceAvailable, setIsVoiceAvailable] = useState(true);
  const [isDisabled, setIsDisabled] = useState(false);
  const [isDeepThinkEnabled, setIsDeepThinkEnabled] = useState(true);
  const [isInternetSearchEnabled, setIsInternetSearchEnabled] = useState(true);
  const [isInputGuildEnabled, setIsInputGuildEnabled] = useState(true);

  const [inputValue, setInputValue] = useState('');
  const [isAppCall, setIsAppCall] = useState(false);
  const [isPageInit, setIsPageInit] = useState(false);
  const [isMetahumanInit, setIsMetahumanInit] = useState(false);
  const [isDeepModeOnly, setIsDeepModeOnly] = useState(false);

  const { isPc } = useWindowWidth();
  const isDeepMode = useIsDeepMode();
  const isOnlineMode = useIsOnlineMode();
  const { setIsDeepMode, setIsOnlineMode } = useChatActions();

  const initializeData = useInitializeData();
  const [tag, setTag] = useState<any>(
    subAppDetail
      ? [
          {
            value: subAppDetail.app_id,
            name: subAppDetail.app_name,
            icon: subAppDetail.app_logo,
            id: subAppDetail.app_id,
            intro: subAppDetail.app_description,
          },
        ]
      : [],
  );

  // const [chatStart, setChatStart] = useState(subAppDetail?true:false);
  const [chatStart, setChatStart] = useState(
    (subAppDetail || appDetail?.appType != AppType.fusion) ? true : false,
  );

  // 添加 ref 来访问 ChatBoxVariableInput 组件
  const variableInputRef = useRef<any>(null);

  const userInputVariables = useMemo(() => {
    if (subAppDetail?.variables || subAppDetail?.workflow?.chatConfig?.variables) {
      const subAppVariables =
        subAppDetail?.variables?.length > 0
          ? subAppDetail?.variables
          : subAppDetail?.workflow?.chatConfig?.variables;
      const subAppVariablesFliter = subAppVariables?.filter(
        (item: any) => item?.type !== VariableInputEnum.custom && item?.required,
      );
      return subAppVariablesFliter || userSelectVariables;
    }
    return (
      workflow?.chatConfig?.variables?.filter(
        (item) => item.type !== VariableInputEnum.custom && item?.required,
      ) || userSelectVariables
    );
  }, [workflow, userSelectVariables, subAppDetail]);

  const chatStarted = useMemo(() => {
    return (
      chatStart || userInputVariables?.length === 0 || userInputVariables?.length === undefined
    );
  }, [chatStart, userInputVariables]);

  useEffect(() => {
    console.log('userInputVariables', userInputVariables, chatStart, chatStarted);
  }, [userInputVariables, chatStart, chatStarted]);

  const [options, setOptions] = useState<AutoCompleteProps['options']>([]);

  const chatConfig = useMemo(() => (workflow ? workflow.chatConfig : {}), [workflow]);

  useEffect(() => {
    if (appDetail?.model?.enableReasoning == false && !subAppDetail) {
      setIsDeepModeOnly(true);
      setIsDeepMode(true);
    } else {
      setIsDeepModeOnly(false);
    }
  }, [appDetail]);

  const initWorkflowConfig = () => {
    const tempChatConfig = subAppDetail ? subAppDetail?.workflow?.chatConfig : chatConfig;
    if (tempChatConfig) {
      if (tempChatConfig?.whisperConfig) {
        setIsVoiceAvailable(tempChatConfig.whisperConfig?.open);
      }

      if (tempChatConfig?.chatInputGuide?.open === true) {
        const mappedInputGuides = inputGuides.map((guide) => ({
          value: guide.content,
        }));
        setGuideQuestions([...mappedInputGuides]);
      } else if (tempChatConfig?.chatInputGuide?.open === false) {
        setGuideQuestions([]);
      }
    }
  };

  useEffect(() => {
    setIsAppCall(inputValue.startsWith('@'));
  }, [inputValue, tag]);

  useEffect(() => {
    // 更新语音功能状态
    const isNewVoiceEnable = fetchConfigStatus(configurations, 'voice_enabled');
    const isSubVoiceEnable = fetchConfigStatus(subAppDetail?.configurations, 'voice_enabled');
    setIsVoiceAvailable(subAppDetail ? isSubVoiceEnable : isNewVoiceEnable);

    // 更新深度思考功能状态
    const isNewDeepThinkEnable = fetchConfigStatus(configurations, 'deep_think');
    const isSubDeepThinkEnable = fetchConfigStatus(subAppDetail?.configurations, 'deep_think');
    setIsDeepThinkEnabled(subAppDetail ? isSubDeepThinkEnable : isNewDeepThinkEnable);

    // 更新联网搜索功能状态
    const isNewInternetSearchEnable = fetchConfigStatus(configurations, 'internet_search');
    const isSubInternetSearchEnable = fetchConfigStatus(
      subAppDetail?.configurations,
      'internet_search',
    );
    setIsInternetSearchEnabled(
      subAppDetail ? isSubInternetSearchEnable : isNewInternetSearchEnable,
    );

    // 更新输入引导功能状态
    const isNewInputGuideEnable = fetchConfigStatus(configurations, 'input_guide');
    const isSubInputGuideEnable = fetchConfigStatus(subAppDetail?.configurations, 'input_guide');
    setIsInputGuildEnabled(subAppDetail ? isSubInputGuideEnable : isNewInputGuideEnable);

    initWorkflowConfig();
  }, [configurations, chatConfig, subAppDetail]);

  // 监听 inputValue 和 isMessageSend 的变化来更新 isDisabled
  useEffect(() => {
    setIsDisabled(inputValue.trim().length === 0 && !isMessageSend && !isVoiceAvailable);
  }, [inputValue, isMessageSend, isVoiceAvailable]);

  useEffect(() => {
    setTag([
      {
        value: subAppDetail?.app_id,
        name: subAppDetail?.app_name,
        icon: subAppDetail?.app_logo,
        id: subAppDetail?.app_id,
        intro: subAppDetail?.app_description,
      },
    ]);
  }, [subAppDetail]);

  const onSelect = (value: string, option: any) => {
    if (isAppCall) {
      setTag([option]);
      if (option?.id) {
        orchestrationService.getAppDetailV2(option?.id, AppWorkbenchType.public).then((app) => {
          setSubAppDetail(app);
        });
      }
      setInputValue('');
      setFusionAppId(option?.id);
    }
    if (value && inputValue !== value && !isAppCall) {
      setInputValue(value);
    }
    setOptions([]);
  };

  const [fusionAppOptions, setFusionAppOptions] = useState<any>([]);

  useEffect(() => {
    if (appDetail?.fusionApp) {
      const options = appDetail.fusionApp.map((app: any) => ({
        value: app.appId,
        name: app.name,
        id: app.appId,
        intro: app.intro,
        icon: app?.icon || app?.appLogo || '',
        label: (
          <div className="flex h-[34px] items-center">
            {/* <SvgIcon icon="hot-fire" color="#C966FF" style={{ marginRight: '10px' }}></SvgIcon> */}
            <AvatarDisplay
              src={app?.icon || (app?.appLogo as string)}
              size={30}
              className="h-[30px] w-[30px]"
            />
            <span style={{ fontWeight: 'bold', marginRight: '10px' }} className="pl-2">
              {app.name}
            </span>
            <span style={{ color: 'grey' }}>{app.intro}</span>
          </div>
        ),
      }));
      setFusionAppOptions(options);
    } else {
      setFusionAppOptions([]);
    }
  }, [appDetail]);

  // const fusionAppOptions = [
  //   {
  //     value: '融合应用',
  //     id: 1,
  //     label: (
  //       <div className="flex items-center h-[34px]">
  //         <SvgIcon icon="hot-fire" color="#C966FF" style={{ marginRight: '10px' }}></SvgIcon>
  //         <span style={{ fontWeight: 'bold', marginRight: '10px' }}>应用推荐</span>
  //         <span style={{ color: 'grey' }}> 各部门应用，一步到位</span>
  //       </div>
  //     ),
  //     unselectable: 'on',
  //   },
  // ];

  useEffect(() => {
    if (tag.length > 0 && options?.length != 0) {
      setOptions([]);
    }
    if (tag?.length == 0) {
      setFusionAppId('');
      setSubAppDetail(null);
      if (isHome) {
        setChatStart(false);
        setHomepageChatStart?.(false);
        setVariables({});
      }
    }
  }, [tag.length]);

  useEffect(() => {
    if (subAppDetail) {
      if (tag?.length > 0 && tag?.[0]?.id == subAppDetail?.app_id) {
        return;
        return;
      }
      // if (!isPageInit) {
      //   setIsPageInit(true)
      // }
      setVariables({});
      // setChatStart(false);
    }
  }, [tag]);

  useEffect(() => {
    if (subAppDetail) {
      if (!isPageInit) {
        setIsPageInit(true);
        return;
      }
      setChatStart(false);
      setHomepageChatStart?.(false);
      // setVariables({});
    }
  }, [subAppDetail]);

  // 合并引导问题列表
  const [guideQuestions, setGuideQuestions] = useState<GuideQuestion[]>([]);

  const fetchInputGuides = async (id: string) => {
    if (!id) return [];
    try {
      const res = await orchestrationService.getAppInputGuide(id);
      if (res.input_guide) {
        const guides = res.input_guide.map((guide: string, index: number) => ({
          id: String(index + 1),
          content: guide,
        }));
        return guides;
      }
      return [];
    } catch (error) {
      return [];
    }
  };

  useEffect(() => {
    const updateGuideQuestions = async () => {
      if (isInputGuildEnabled) {
        let updatedInputGuides = inputGuides;
        if (subAppDetail) {
          updatedInputGuides = await fetchInputGuides(subAppDetail?.app_id);
        }
        if (updatedInputGuides && updatedInputGuides.length > 0) {
          const mappedInputGuides = updatedInputGuides.map((guide) => ({
            value: guide.content,
          }));
          setGuideQuestions([...mappedInputGuides]);
        } else {
          setGuideQuestions([]);
        }
      } else {
        setGuideQuestions([]);
      }
      initWorkflowConfig();
    };
    updateGuideQuestions();
  }, [inputGuides, isInputGuildEnabled, chatConfig, subAppDetail]);

  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);
  const [dropdownHeight, setDropdownHeight] = useState<number>(300);

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const { fetchInitialInfo } = useConfigActions();
  const [verifyBalanceAvailable, setVerifyBalanceAvailable] = useState(true);
  // 验证联网搜索余额
  const verifyBalance = async (appId: string) => {
    if (subAppDetail?.app_id || appId) {
      const res = await orchestrationService.verifyBalance(subAppDetail?.app_id || appId);
      setVerifyBalanceAvailable(res);
    }
  };
  useEffect(() => {
    const init = async () => {
      fetchInitialInfo();
    };
    init();
    const queryParams = new URLSearchParams(location.search);
    const appId = queryParams.get('appId') || '';
    verifyBalance(appId);
  }, []);

  // 处理输入变化，匹配引导问题
  const handleSearch = (value: string) => {
    if (value.startsWith('@') && fusionAppOptions?.length > 0) {
      // 提取@后面的内容
      const searchText = value.slice(1).trim().toLowerCase();
      const matchedApp = fusionAppOptions
        .filter((option: any) => {
          // 如果@后没有内容，显示全部
          if (!searchText) return true;
          return (
            (option.name && option.name.toLowerCase().includes(searchText)) ||
            (option.intro && option.intro.toLowerCase().includes(searchText))
          );
        })
        .map((option: any) => {
          if (!searchText) return option;
          // 高亮匹配的 searchText
          const highlight = (text: string) => {
            if (!text) return '';
            const reg = new RegExp(`(${searchText})`, 'gi');
            return text.replace(reg, '<span style="color: #1B6DFA;">$1</span>');
          };
          return {
            ...option,
            label: (
              <div className="flex h-[34px] items-center">
                <AvatarDisplay src={option.icon} size={30} className="h-[30px] w-[30px]" />
                <span
                  style={{ fontWeight: 'bold', marginRight: '10px' }}
                  className="pl-2"
                  dangerouslySetInnerHTML={{ __html: highlight(option.name) }}
                />
                <span
                  style={{ color: 'grey' }}
                  dangerouslySetInnerHTML={{ __html: highlight(option.intro) }}
                />
              </div>
            ),
          };
        });
      // tag?.length == 0 && setOptions(matchedApp);
      setOptions(matchedApp);
      if (isHome) {
        const height = calculateDropdownHeight(matchedApp.length);
        setDropdownHeight(height);
      }
    } else {
      setOptions([]);
    }
    if (value?.startsWith('@')) {
      return;
    }
    if (value && value.trim() !== '') {
      // 匹配输入内容与引导问题
      const matchedQuestions = guideQuestions
        .filter((question) => question.value.toLowerCase().includes(value.toLowerCase()))
        .map((question, index) => ({
          value: question.value,
          label: <div style={{ padding: '8px 12px' }}>{question.value}</div>,
        }));
      setOptions(matchedQuestions);
      // 计算并设置下拉框高度
      if (isHome) {
        const height = calculateDropdownHeight(matchedQuestions.length);
        setDropdownHeight(height);
      }
    } else {
      setOptions([]);
    }
  };

  const autoCompleteRef = useRef<any>(null);

  useEffect(() => {
    !inputValue && setOptions([]);
  }, [inputValue]);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e?.key === 'Enter' && e?.keyCode === 13 && !e?.shiftKey) {
      if (isAppCall && options?.length && options.length > 0) {
        setInputValue('');
        return;
      }

      e.preventDefault();
      if (!inputValue) {
        return;
      }

      if (licenseFlag && !initializeData?.is_license_valid) {
        handleActivateClick();
        return;
      }
      if (isHome) {
        if (inputValue && onChatStart) {
          onChatStart(inputValue);
        }
      } else {
        handleSend(inputValue);
        setTimeout(() => {
          setInputValue('');
        }, 0);
      }
    }

    // 监听上下键，当显示下拉菜单时，获取高亮选项内容
    if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && options && options.length > 0) {
      // 延迟执行以确保DOM已更新
      setTimeout(() => {
        const highlightedItem = document.querySelector('.ant-select-item-option-active');
        if (highlightedItem) {
          const content = highlightedItem.querySelector(
            '.ant-select-item-option-content',
          )?.textContent;
          if (isAppCall) {
            return;
          }
          if (content) {
            setInputValue(content);
          }
        }
      }, 10);
    }

    // 处理Tab键，自动补全当前高亮选中的值
    if (e.key === 'Tab' && options && options.length > 0 && !isAppCall) {
      e.preventDefault(); // 阻止默认的Tab行为

      // 延迟执行以确保DOM已更新
      setTimeout(() => {
        const highlightedItem = document.querySelector('.ant-select-item-option-active');
        if (highlightedItem) {
          const content = highlightedItem.querySelector(
            '.ant-select-item-option-content',
          )?.textContent;
          if (content) {
            setInputValue(content);
            // 清空选项，关闭下拉菜单
            setOptions([]);
          }
        } else if (options.length > 0) {
          // 如果没有高亮项但有选项，选择第一个
          const firstOption = options[0];
          if (firstOption && firstOption.value) {
            setInputValue(String(firstOption.value));
            // 清空选项，关闭下拉菜单
            setOptions([]);
          }
        }
      }, 10);
    }
  };

  const handleBtnClicked = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    if (isHome) {
      if (inputValue.trim().length == 0) {
        isVoiceAvailable && changeInputType();
      } else {
        if (inputValue && onChatStart) {
          onChatStart(inputValue);
        }
      }
    } else {
      if (isMessageSend) {
        handleInterrupt();
      } else {
        if (inputValue.trim().length == 0) {
          isVoiceAvailable && changeInputType();
        } else {
          handleSend(inputValue);
          setInputValue('');
        }
      }
    }
  };

  // 处理提交按钮点击事件
  const handleSubmitClick = () => {
    // 如果有变量输入组件，调用其 validateAndStart 方法
    if (variableInputRef.current) {
      const isValid = variableInputRef.current.validateAndStart();
      if (isValid) {
        // 验证通过，开始聊天
        setChatStart(true);
        setHomepageChatStart?.(true);
      }
    } else {
      // 没有变量输入组件，直接开始聊天
      setChatStart(true);
      setHomepageChatStart?.(true);
    }
  };

  // 计算下拉框高度
  const calculateDropdownHeight = (optionCount: number) => {
    const optionHeight = 44; // 每个选项的高度
    const minHeight = optionHeight * 1 + 35; // 最小高度
    const maxHeight = optionHeight * 6 + 35; // 最大高度

    const calculatedHeight = optionCount * optionHeight + 35;
    // message.info(Math.max(minHeight, Math.min(calculatedHeight, maxHeight)) + '-' + calculatedHeight + '-' + minHeight + '-' + maxHeight)
    return Math.max(minHeight, Math.min(calculatedHeight, maxHeight));
  };

  const textareaStyle = {
    borderRadius: '6px',
    resize: 'none' as const,
    overflowY: 'scroll' as const,
    width: '100%',
    outline: 'none',
    boxShadow: 'none',
    // backgroundColor: '#F7F8FA',
    backgroundColor: 'transparent',
    scrollbarWidth: 'none' as const,
    flexGrow: 1,
    borderWidth: 0,
    lineHeight: '24px',
  };

  const dropdownRender = (menu: React.ReactNode) => (
    <div style={{ position: 'relative', paddingTop: isAppCall ? '30px' : '0px' }}>
      <div
        style={{
          position: 'absolute',
          display: isAppCall ? 'flex' : 'none',
          top: 0,
          right: 0,
          zIndex: 1001,
          width: '100%',
          padding: '0px 10px',
          height: '30px',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <div className="text-[14px] font-normal text-[#86909C]">{isAppCall && '选择应用'}</div>
        {/* <Button
          size="small"
          type="text"
          icon={<CloseOutlined />}
          onClick={() => {
            setOptions([]);
          }}
        ></Button> */}
      </div>
      {menu}
    </div>
  );

  const buttonRender = (className?: string) => {
    return (
      <div className={className}>
        {isDeepThinkEnabled &&
          (isDeepModeOnly && isDeepMode ? (
            <Tooltip title="该模型仅支持深度思考">
              <span>
                <Button
                  disabled
                  style={{
                    border: isDeepMode ? '1px solid #BADDFF' : '1px solid #E5E6EB',
                    color: isDeepMode ? 'var(--brand-color)' : '#4C4C4C',
                    backgroundColor: isDeepMode ? 'var(--brand-color-light)' : '#fff',
                    padding: '0px 10px',
                  }}
                >
                  <SvgIcon
                    icon="ai-chat-think"
                    size={16}
                    color={isDeepMode ? 'var(--brand-color)' : '#4C4C4C'}
                  />
                  深度思考
                </Button>
              </span>
            </Tooltip>
          ) : (
            <Button
              style={{
                border: isDeepMode ? '1px solid #BADDFF' : '1px solid #E5E6EB',
                color: isDeepMode ? 'var(--brand-color)' : '#4C4C4C',
                backgroundColor: isDeepMode ? 'var(--brand-color-light)' : '#fff',
                padding: '0px 10px',
              }}
              onClick={() => {
                setIsDeepMode(!isDeepMode);
              }}
            >
              <SvgIcon
                icon="ai-chat-think"
                size={16}
                color={isDeepMode ? 'var(--brand-color)' : '#4C4C4C'}
              />
              深度思考
            </Button>
          ))}

        {isInternetSearchEnabled && verifyBalanceAvailable && (
          <Button
            style={{
              border: isOnlineMode ? '1px solid #BADDFF' : '1px solid #E5E6EB',
              color: isOnlineMode ? 'var(--brand-color)' : '#4C4C4C',
              backgroundColor: isOnlineMode ? 'var(--brand-color-light)' : '#fff',
              padding: '0px 10px',
            }}
            onClick={() => {
              setIsOnlineMode(!isOnlineMode);
            }}
          >
            <SvgIcon
              icon="ai-chat-search"
              size={16}
              color={isOnlineMode ? 'var(--brand-color)' : '#4C4C4C'}
            />
            联网搜索
          </Button>
        )}
      </div>
    );
  };

  useEffect(() => {
    // if (fusionAppId && subAppDetail) {
    //   console.log('subAppDetail', subAppDetail);
    //   setTag([{
    //     value: subAppDetail.app_name,
    //     icon: subAppDetail.app_logo,
    //     id: subAppDetail.app_id,
    //     intro: subAppDetail.app_description,
    //   }])
    // }
    if (!fusionAppId) {
      setTag([]);
    }
  }, [fusionAppId]);

  // const userInputVariables = useMemo(() => {
  //   if (subAppDetail?.variables) {
  //     return subAppDetail?.variables;
  //   }
  //   return (
  //     workflow?.chatConfig?.variables?.filter((item) => item.type !== VariableInputEnum.custom) ||
  //     userSelectVariables
  //   );
  // }, [workflow, userSelectVariables, subAppDetail]);

  // const [chatStart, setChatStart] = useState(false);
  // const chatStarted = chatStart || userInputVariables?.length === 0 || userInputVariables?.length === undefined;

  const [marginBottom, setMarginBottom] = useState(20);

  useEffect(() => {
    if (tag?.length == 0) {
      setMarginBottom(25);
    } else {
      setMarginBottom(75);
    }
  }, [tag]);

  // 1. 新增分页 state
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 3;
  const totalItems = userInputVariables?.length || 0;
  const totalPages = Math.ceil(totalItems / pageSize);

  // 校验所有变量的必填项是否都填写
  const isAllRequiredFilled = useMemo(() => {
    return (userInputVariables || []).every(
      (item: VariableItemType) => !item.required || !!flowVariables[item.key],
    );
  }, [userInputVariables, flowVariables]);

  const [isActive, setIsActive] = useState(false);
  const [isHover, setIsHover] = useState(false);
  const isInChatPage = location.pathname.includes('/apps/chat') || location.pathname.includes('/apps/fusion');


  // 使用 useRequest 获取数字人权限配置
  const { run: fetchMetahumanPermissionConfig } = useRequest(
    async (appId: string) => {
      setIsPermissionConfigLoading(true);
      try {
        const config = await metahumanService.getMetahumanPermissionConfig(appId, isInChatPage ? AppWorkbenchType.public : AppWorkbenchType.manage);
        setPermissionConfig(config);
        setAppId(appId);
        setVirtualAvatarEnabled(config.metahumanEnabled);
        setVirtualAvatarId(config.avatarId);
        setVirtualSpeakerId(config.speakerId);
        setVirtualAvatarUrl(config.previewAvatarUrl);
        setVirtualAvatarName(config.avatarName || config.avatarId);
        setVirtualAvatarVoice(config.speakerName || config.speakerId);
        return config;
      } catch (error) {
        setPermissionConfig(null);
      } finally {
        setIsPermissionConfigLoading(false);
      }
    },
    {
      manual: true, // 手动触发，不自动执行
    }
  );

  useEffect(() => {
    console.log('fusionAppId', fusionAppId)
    if (!isMetahumanInit) {
      setIsMetahumanInit(true);
      return;
    }
    if (appDetail?.appType === AppType.fusion) {
      storeStop();
      if (fusionAppId) {
        initializeData?.enableMetahuman && fetchMetahumanPermissionConfig(fusionAppId);
      } else {
        reset();
      }
    }
  }, [fusionAppId]);

  return (
    <div className={`qa-message-send-input w-full ${isPc?'':'bg-white'}`}>
      {!isPc && buttonRender('flex items-center justify-start gap-2 mb-1 ml-1')}
      <div
        className={`
          message-input 
          relative
          flex 
          w-full 
          flex-col
          rounded-[12px]
          ${isPc ? 'p-4' : 'p-2'}
        `}
        // onMouseEnter={() => setIsHover(true)}
        // onMouseLeave={() => setIsHover(false)}
        onFocus={() => setIsActive(true)}
        onBlur={() => setIsActive(false)}
        style={
          isActive
            ? {
                background: `linear-gradient(white, white) padding-box, linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%) border-box`,
                border: '2px solid transparent',
                boxShadow: '0px 8px 16px 0px #056EFF29',
              }
            : {
                border: '2px solid transparent',
                boxShadow: `inset 0 0 0 1px var(--brand-color-hover)`,
              }
        }
        onMouseEnter={(e) => {
          setIsHover(true);
          if (!isActive && isHover) {
            e.currentTarget.style.boxShadow = `inset 0 0 0 1px var(--brand-color-hover)`;
          }
        }}
        onMouseLeave={(e) => {
          setIsHover(false);
          if (!isActive) {
            e.currentTarget.style.boxShadow = `inset 0 0 0 1px var(--line-2)`;
          }
        }}
      >
        {tag?.length > 0 && (
          <div style={{ marginBottom: '0px' }}>
            {tag?.map((item: any, index: any) => {
              return (
                <Tag
                  className="h-[30px] w-full items-center rounded-[5px] !bg-[transparent] !px-[4px] text-[16px]"
                  bordered={false}
                  key={index}
                  // closable
                  // onClose={() => {
                  //   setTag([]);
                  // }}
                >
                  <div className={`mb-[10px] flex w-full items-center justify-between border-b border-[#F2F3F5] ${isPc ? 'pb-4' : 'pb-2'}`}>
                    <div className="flex min-w-0 flex-1 items-center">
                      <AvatarDisplay
                        src={item.icon as string}
                        size={30}
                        className="h-[30px] w-[30px] flex-shrink-0"
                      />
                      <div className="pl-2 text-[14px] font-bold text-[#1D2129]">{item.name}</div>
                      <div className="pl-2 text-[14px] font-font-weight-400 text-text-2">
                        为您回答
                      </div>
                    </div>
                    <div>
                      <CloseOutlined
                        onClick={() => {
                          setTag([]);
                        }}
                      />
                    </div>
                  </div>
                </Tag>
              );
            })}
          </div>
        )}
        <div
          className={`flex ${
            isPc && (isDeepThinkEnabled || isInternetSearchEnabled || !chatStarted)
              ? 'flex-col'
              : !chatStarted
              ? 'flex-col'
              : 'flex-row'
          }`}
        >
          {!chatStarted && (
            <div className="w-full">
              <div className="text-cn-14 text-text-3">请先回答以下问题</div>
              <ChatBoxVariableInput
                ref={variableInputRef}
                chatStart={chatStarted}
                setChatStart={setChatStart}
                currentPage={currentPage}
                pageSize={pageSize}
              />
            </div>
          )}

          {voice && (
            <div
              className={`w-full ${
                isPc && (isDeepThinkEnabled || isInternetSearchEnabled) ? 'pb-2' : 'px-2'
              } `}
            >
              <FunasrRecorder
                isMessageSend={isMessageSend}
                onInterrupt={onInterrupt}
                onStop={(inputValue: string) => {
                  console.log('isMessageSend', isMessageSend, inputValue);

                  if (isMessageSend) {
                    onInterrupt?.();
                  }
                  onVoiceStop?.(inputValue);
                }}
                onSTT={onSTT}
                onSwitch={changeInputType}
                className="flex h-full w-full items-center justify-center"
              />
            </div>
          )}

          <div
            style={{ display: chatStarted && !voice ? 'flex' : 'none', width: '100%' }}
            className="rounded-[6px]"
          >
            <AutoComplete
              ref={autoCompleteRef}
              className="ant-select auto-complete-input"
              options={options}
              maxLength={20000}
              onSelect={onSelect}
              onSearch={handleSearch}
              getPopupContainer={(triggerNode) => triggerNode.parentElement}
              defaultActiveFirstOption={true}
              dropdownStyle={
                isHome
                  ? {
                      position: 'absolute',
                      bottom: '100%',
                      marginBottom: marginBottom,
                      zIndex: 2000,
                      left: 0,
                      borderRadius: '12px',
                      width: '100%',
                      // height: `${dropdownHeight}px`,
                    }
                  : {
                      // top: options?.length == 1 ? '100%' : 'unset',
                      // marginTop: options?.length == 1 ? (tag?.length == 0 ? -175 : -225) : 'unset',
                      // bottom: options?.length == 1 ? 'unset' : '100%',

                      top: 'unset',
                      marginTop: 'unset',
                      bottom: '100%',

                      // bottom: '100%',
                      
                      marginBottom: marginBottom,
                      position: 'absolute',
                      left: 0,
                      zIndex: 2000,
                      borderRadius: '12px',
                      width: '100%',
                    }
              }
              dropdownRender={dropdownRender}
              value={inputValue}
              style={{
                width: '100%',
                flex: '1 1 auto',
                height: '100%',
              }}
            >
              <TextArea
                id="question"
                className="border:none"
                autoSize={{ minRows: isPc ? 2 : 1, maxRows: 8 }}
                onChange={(e) => {
                  setInputValue(e.target.value);
                  handleSearch(e.target.value);
                }}
                value={inputValue}
                onKeyDown={handleKeyDown}
                placeholder={
                  appDetail?.appType == AppType.fusion && tag?.length == 0
                    ? '随时@你想要的应用，使用对应能力对话'
                    : isPc
                    ? '输入问题，发送【Enter】/ 换行【Shift+Enter】'
                    : '输入问题'
                }
                style={textareaStyle}
              />
            </AutoComplete>
          </div>

          <div className="flex justify-between">
            {isPc && buttonRender('flex items-center justify-center gap-2')}
            {!isPc && <div></div>}
            <div
              className="flex items-center justify-center gap-2"
              style={{ display: !chatStarted ? 'unset' : 'none' }}
            >
              {totalPages > 1 && (
                <>
                  <Button
                    icon={
                      <SvgIcon
                        icon="ai-chat-pre"
                        color={currentPage === 1 ? '#E5E6EB' : '#86909C'}
                        size={32}
                      ></SvgIcon>
                    }
                    disabled={currentPage === 1}
                    onClick={() => setCurrentPage((prev) => prev - 1)}
                    type="text"
                    className="ml-2 mr-4"
                  ></Button>

                  <span style={{ color: '#1D2129' }}>{currentPage}</span>
                  <span style={{ color: currentPage === totalPages ? '#1D2129' : '#86909C' }}>
                    /
                  </span>
                  <span style={{ color: currentPage === totalPages ? '#1D2129' : '#86909C' }}>
                    {totalPages}
                  </span>

                  <Button
                    icon={
                      <SvgIcon
                        icon="ai-chat-next"
                        color={currentPage === totalPages ? '#E5E6EB' : '#86909C'}
                        size={32}
                      ></SvgIcon>
                    }
                    disabled={currentPage === totalPages}
                    onClick={() => setCurrentPage((prev) => prev + 1)}
                    type="text"
                    className="ml-4 mr-2"
                  ></Button>
                </>
              )}

              <Button
                type="primary"
                onClick={handleSubmitClick}
                className={`${isPc ? 'ml-2' : ''}`}
                disabled={!isAllRequiredFilled}
              >
                提交
              </Button>
            </div>

            <div
              className="items-end justify-center"
              style={{ display: chatStarted ? 'flex' : 'none' }}
            >
              {isHome ? (
                <Button
                  id="submit"
                  type="primary"
                  icon={
                    isMessageSend ? (
                      <SvgIcon icon="ic_stop" size={18} />
                    ) : inputValue.trim().length == 0 ? (
                      !isVoiceAvailable ? (
                        <SvgIcon icon="ai-chat-send" size={18} />
                      ) : voice ? (
                        <SvgIcon icon="ai-chat-text" size={18} />
                      ) : (
                        <SvgIcon icon="ai-chat-voice" size={18} />
                      )
                    ) : (
                      <SvgIcon icon="ai-chat-send" size={18} />
                    )
                  }
                  onClick={handleBtnClicked}
                  className={`${
                    isDisabled ? 'pointer-events-none bg-[#CCCCCC]' : 'bg-[var(--brand-color)]'
                  }`}
                />
              ) : (
                <Button
                  id="submit"
                  type="primary"
                  icon={
                    isMessageSend ? (
                      <SvgIcon icon="ic_stop" size={18} />
                    ) : inputValue.trim().length == 0 ? (
                      !isVoiceAvailable ? (
                        <SvgIcon icon="ai-chat-send" size={18} />
                      ) : voice ? (
                        <SvgIcon icon="ai-chat-text" size={18} />
                      ) : (
                        <SvgIcon icon="ai-chat-voice" size={18} />
                      )
                    ) : (
                      <SvgIcon icon="ai-chat-send" size={18} />
                    )
                  }
                  onClick={handleBtnClicked}
                  className={`${
                    isDisabled ? 'pointer-events-none bg-[#CCCCCC]' : 'bg-[var(--brand-color)]'
                  }`}
                />
              )}
            </div>
          </div>
        </div>
        <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
        {isHome && (
          <style>{`
          .auto-complete-input .ant-select-dropdown {
            top: unset !important;
            bottom: 100% !important;
            left: 0 !important;
            margin-bottom: ${marginBottom}px !important;
          }
          #submit .ant-btn-icon {
            display: flex !important;
          }
          .message-input .ant-input-outlined {
            background: transparent !important;
          }
        `}</style>
        )}
      </div>
    </div>
  );
};

export default memo(MessageSendInput);
